package com.ptszyxx.popose.module.main.expression.vm;

import android.app.Application;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.enums.EditEnum;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.common.utils.YBusUtil;
import com.ysg.base.BaseViewModel;
import com.ysg.binding.command.BindingCommand;
import com.ysg.bus.event.SingleLiveEvent;
import com.ysg.http.BaseResponse;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.http.data.CommonRepository;
import com.ysg.http.data.entity.expression.ExpressionEntity;
import com.ysg.utils.YCollectionUtil;
import com.ysg.utils.YDbUtils;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import com.ysg.utils.YUserUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;

public class ExpressionVM extends BaseViewModel<CommonRepository> {
    public ObservableField<String> input = new ObservableField<>();

    public ExpressionVM(@NonNull Application application, CommonRepository model) {
        super(application, model);
    }

    public UIChangeObservable uc = new UIChangeObservable();

    public class UIChangeObservable {
        public SingleLiveEvent onRefreshEvent = new SingleLiveEvent<>();
    }

    public BindingCommand onCloseCommand = new BindingCommand(()-> YActivityUtil.getInstance().close(this));
    public BindingCommand onSaveCommand = new BindingCommand(()-> onSave());

    public void onSave(){
        if(YStringUtil.isEmpty(input.get())){
            YToastUtil.showShort(R.string.hint_input);
            return;
        }

        if (YStringUtil.isNotEmpty(input.get())){
            String[] split = input.get().split("@");
            List<ExpressionEntity> list = new ArrayList<>();
            if (YCollectionUtil.isNotEmpty(split)){
                for (String content: split) {
                    ExpressionEntity entity = new ExpressionEntity();
                    entity.setIsCommon("0");
                    entity.setContent(content.trim());
                    list.add(entity);
                }
                if (YDbUtils.getInstance().saveExpression(list)){
                    YToastUtil.showShort(R.string.save_success);
                    requestExpression();
                    input.set("");
                }
            }
        }
    }

    public void requestExpression() {
        List<ExpressionEntity> expression = YDbUtils.getInstance().findExpression();
        uc.onRefreshEvent.setValue(expression);
    }

    public void requestExpressionDel(ExpressionEntity entity) {
        int id = YDbUtils.getInstance().deleteExpression(entity);
        Log.e("id", "" + id);
        YToastUtil.showShort(R.string.success_delete);
        requestExpression();
    }

}
